package ac.svn.accesscontrol.ui.helper;

import java.util.Set;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import ac.svn.accesscontrol.manager.SVNInfoManager;
import ac.svn.accesscontrol.store.SVNGroup;
import ac.svn.accesscontrol.store.SVNUser;
import ac.svn.accesscontrol.ui.IUIConstants;
import ac.svn.accesscontrol.ui.UIComponentLibrary;

public class SVNItemFilter 
{
    private JTree svnTree;
    private Thread thread;
    private String searchText = ""; 
    public SVNItemFilter()
    {
	svnTree = (JTree) UIComponentLibrary.getComponent(IUIConstants.C_USERS_TREE);
	thread = new Thread(new Runnable() {

	    @Override
	    public void run() {
		svnTree.clearSelection();
		Set<String> compIds = UIComponentLibrary.getComponentIds();
		SVNInfoManager infoManager = SVNInfoManager.getInfoManager();

		for(String compIdentifier : compIds)
		{

		    //Final text in which references are searched.
		    String finalText = "";

		    if(compIdentifier.contains("#"))
		    {
			//Find Id of components
			String id = compIdentifier.substring(0,compIdentifier.indexOf('#'));

			if(id != null && false == id.isEmpty())
			{
			    //Check if any SVNUser is present for this id
			    SVNUser user = infoManager.getSvnUser(id);
			    if(null != user)
			    {
				finalText = String.format("%s|%s|%s",finalText,user.getUserName(),user.getUserAlias());
			    }
			}
		    }
		    else
		    {
			finalText = compIdentifier;
			//Check if any Group is there with extracted id.
			SVNGroup group = infoManager.getGroup(compIdentifier);
			if(null != group)
			{
			    finalText = String.format("%s|%s|%s",finalText,group.getGroupName(),group.getGroupAlias());
			}else
			{
			    finalText = "";
			}
		    }

		    if(finalText.toLowerCase().contains(searchText.toLowerCase()))
		    {
			System.out.println(String.format("Final Test: %s, Search Text: %s" , finalText,searchText));
			try
			{
			    DefaultMutableTreeNode  node = (DefaultMutableTreeNode) UIComponentLibrary.getComponent(compIdentifier);
			    TreeNode[] nodes = ((DefaultTreeModel)svnTree.getModel()).getPathToRoot(node);  
			    svnTree.setExpandsSelectedPaths(true);                
			    svnTree.getSelectionModel().addSelectionPath(new TreePath(nodes));
			}
			catch(ClassCastException ce)
			{

			}					
		    }


		}
	    }
	});

    }

    public void findNode(String nodeName)
    {
	this.searchText = nodeName;
	if(thread.isAlive())
	{
	    thread.interrupt();
	}
	thread.run();
    }

    public void clearSelection() {
	svnTree.clearSelection();		
    }
}
